package cn.hzc.fortess.config;

import cn.hutool.core.date.DateUtil;
import cn.hzc.fortess.core.common.GlobalErrorView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import java.util.Date;

@Configuration
@ConditionalOnBean(ServletContext.class)
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    /**
     * 默认错误页面，返回json
     */
    @Bean("error")
    public GlobalErrorView error() {
        return new GlobalErrorView();
    }


    /**
     * 时间转化器
     */
    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
        if ((initializer != null ? initializer.getConversionService() : null) != null) {
            GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }

    public class StringToDateConverter implements Converter<String, Date> {
        @Override
        public Date convert(String dateString) {
            return DateUtil.parse(dateString);
        }
    }


//    private static class MvcAdapter {
//
//        public static RequestMappingHandlerAdapter requestMappingHandlerAdapter(
//                RequestMappingHandlerAdapter original,
//                FastJsonHttpMessageConverter fastJsonHttpMessageConverter
//                ) {
//
//            List<HttpMessageConverter<?>> list = new LinkedList<>();
//
//            StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
//            stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316
//            list.add(stringHttpMessageConverter);
//
//            list.add(fastJsonHttpMessageConverter);
//            original.setMessageConverters(list);
//            return original;
//        }
//    }

}


